'''
Created on Sep 7, 2012

@author: petrina
'''
from link_indicator import Link_indicator
from indiutils import Indiutils
import logging

class Buffer_speed_index(Link_indicator):
    '''
    Calculates the Buffer-Speed-Index for every time interval (using aggregated fcd-data).
    
    Formula for calculating the indicator: 
       bsi_i = 100 * (ats_i - wts_i)/ats_i 
            where:
                -  bsi_i ... buffer speed index at the time interval i 
                -  wts_i ... worst case travel speed at the time interval i 
                -  ats_i ... average travel speed at the time interval i 
             
    The 5th percentile travel speed acts as worst case travel speed.   
    
    unit: percent (%)
    '''


    def __init__(self, link):
        '''        
        @param link: Link-object (containing valid records and timeseries) 
        '''
        
        Link_indicator.__init__(self, link)
        self._name = 'Buffer-Speed-Index'
        self._mr_name =  'buffer_speed_idx'
        self._unit = '%'
        #self.unit.__doc__ = 'percent (%)'
        
        self._create_title(link.id, link.direction)
        
        logging.debug("Buffer_speed_index: created new Buffer_speed_index")
        
    #----------------------public methods of the class-------------------------

    def calculate(self):
        '''
        @return: calculates the buffer speed index for every time interval as list of Result_values
        '''
        
        logging.info("Buffer_speed_index: staring to calculate the Buffer-Speed-Index")
        
        utils = Indiutils()
        p05 = utils.p5_speed(self._link.timeseries)
        ats = utils.calc_average_of(self._link.records, "speed")
        self._values = []
        
        # build the buffer speed index for every time interval
        for i in range(self._intervals):
            # treat empty lists (= no measurement)
            value = (ats[i] - p05[i]) * 100/ats[i] if p05[i] is not None and ats[i] is not None else None
            self._values.append(value)
        
        logging.debug("Buffer_speed_index: finished calculating the Buffer-Speed-Index ")

        return self._values